﻿Imports System.Data.OleDb

Public Class EditQuiz
    Inherits System.Web.UI.Page

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Try

        
        If (Not Page.IsPostBack) Then
            If (Page.Request.QueryString("QuizId") <> Nothing) Then
                pnlFields.Visible = True
                Dim selectedQuiz As QuizManagement = New QuizManagement()
                Dim dr As OleDbDataReader = selectedQuiz.SelectQuizByQuizId(Convert.ToInt32(Request.QueryString("QuizId")))

                If dr.HasRows Then
                    dr.Read()
                    If Not IsDBNull(dr("QuizName")) Then txtName.Text = dr("QuizName")
                    If Not IsDBNull(dr("QuizDescription")) Then txtDescription.Text = dr("QuizDescription")
                End If

                
                loadExistingTags()

            Else
                pnlFields.Visible = False
            End If
        End If
        Catch ex As Exception

        End Try
    End Sub

    Public Sub loadExistingTags()
        Try


            'load existing tags 
            Dim loadTags As TagsManagement = New TagsManagement()

            Dim loadTagsString As String = ""

            Dim dr2 As OleDbDataReader = loadTags.SelectTagsByQuizIdVisible(Convert.ToInt32(Request.QueryString("QuizId")))

            If dr2.HasRows Then
                Do While dr2.Read()
                    If Not IsDBNull(dr2("TagName")) Then loadTagsString = loadTagsString + "<li>" + (dr2("TagName")).ToString() + "</li>"
                Loop
            End If

            ltrTags.Text = loadTagsString

            'load tags for auto

            Dim myTags As TagsManagement = New TagsManagement()
            Dim dr3 As OleDbDataReader = myTags.SelectAllTagsVisible()

            Dim availableTags As String = ""

            If dr3.HasRows Then
                Do While dr3.Read()
                    If Not IsDBNull(dr3("TagName")) Then availableTags = availableTags + (dr3("TagName")).ToString() + ","
                Loop
            End If

            hdnDBTags.Value = availableTags
        Catch ex As Exception

        End Try
    End Sub

    Protected Function getPicture(ByVal url As String)
        Try

        
            Return "../" + url

        Catch ex As Exception
            Return Nothing
        End Try
    End Function

    Protected Function getDate(ByVal creationDate As DateTime)
        Try

            Return creationDate.ToShortDateString()

        Catch ex As Exception
            Return Nothing
        End Try
    End Function



    Public Sub btnUpdate_Quiz(sender As Object, e As EventArgs)

        If (hdnSelectedTags.Value <> "") Then


            Dim updateDate = New DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day)

            Dim myGuid As New Guid
            myGuid = Guid.NewGuid()

            Dim fileIsAnImage As Boolean = False
            Dim fileName As String
            Dim myFileName As String = String.Empty

            If (fuImage.HasFile) Then

                fileName = Server.HtmlEncode(fuImage.FileName)
                Dim extension As String = System.IO.Path.GetExtension(fileName)

                If (extension = ".jpg") Then
                    myFileName = myGuid.ToString() + ".jpg"
                    fileIsAnImage = True
                ElseIf (extension = ".png") Then
                    myFileName = myGuid.ToString() + ".png"
                    fileIsAnImage = True
                End If


                If (fileIsAnImage) Then
                    Dim filePath = Request.MapPath("../Pictures/Quiz") + "/" + myFileName
                    fuImage.SaveAs(filePath)

                    Dim userId As Int32 = New aspnet_UsersManagement().SelectUserIDByUsername(User.Identity.Name)
                    Dim editQuiz As QuizManagement = New QuizManagement()
                    editQuiz.UpdateQuizByQuizIDWithPicture(Convert.ToInt32(Request.QueryString("QuizId")), txtName.Text, txtDescription.Text, updateDate, "Pictures/Quiz/" + myFileName)
                    SqlDataSourceGetQuizes.DataBind()
                    grvQuiz.DataBind()

                    updateTags()
                    loadExistingTags()

                    lblMessage.Text = "Update done"

                    '  Response.Redirect("EditQuiz.aspx?QuizId=" + Request.QueryString("QuizId"))


                Else
                    lblMessage.Text = "Only jpeg or png files are allowed"
                End If
            Else

                Dim editQuiz As QuizManagement = New QuizManagement()
                editQuiz.UpdateQuizByQuizIDWithoutPicture(Convert.ToInt32(Request.QueryString("QuizId")), txtName.Text, txtDescription.Text, updateDate)
                updateTags()
                loadExistingTags()
                lblMessage.Text = "Update is done"


            End If

            grvQuiz.DataBind()
        Else
            lblMessage.Text = "A Quiz must contain a tag. Update not done"
        End If
    End Sub

    Public Sub updateTags()
        'update tags
        Dim writtenTags As String = hdnSelectedTags.Value
        Dim arrayOfWrittenTags As IList(Of String) = writtenTags.Split(",").ToList()

        Dim myTags As TagsManagement = New TagsManagement()
        Dim dr As OleDbDataReader = myTags.SelectAllTagsVisible()

        Dim availableTags As ArrayList = New ArrayList()

        If dr.HasRows Then
            Do While dr.Read()
                If Not IsDBNull(dr("TagName")) Then availableTags.Add((dr("TagName")))
            Loop
        End If

        Dim aCookie As HttpCookie = Request.Cookies("userIdCookie")
        Dim myuserId = Convert.ToInt32(aCookie.Value)

        For index = 0 To arrayOfWrittenTags.Count - 1
            'add new tag to tag table
            If (Not availableTags.Contains(arrayOfWrittenTags(index))) Then
                Dim addTag As TagsManagement = New TagsManagement()

                addTag.InsertTags(myuserId, arrayOfWrittenTags(index))

                'add ranking points
                Dim myPoints As Users_RankingPointsManagement = New Users_RankingPointsManagement()
                Dim rankingPointsId As Int32 = myPoints.SelectRankingPointsByType("Add Tag")

                myPoints.InsertUsersRankingPoints(myuserId, rankingPointsId)

            End If

        Next

        'delete quiz_tags associated with this quiz
        Dim deleteTag As TagsManagement = New TagsManagement()
        deleteTag.DeleteQuizTagByQuizId(Request.QueryString("QuizId"))

        'add quiz tags

        For index = 0 To arrayOfWrittenTags.Count - 1
            'add new tag to tag table
            Dim currentTag As String = arrayOfWrittenTags(index).ToString()

            Dim addTag As TagsManagement = New TagsManagement()
            Dim tagId As Int32 = addTag.SelectTagIdByTagName(currentTag)

            addTag.InsertQuizTag(Convert.ToInt32(Request.QueryString("QuizId")), tagId)


        Next

    End Sub
End Class